package api;

import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;

@WebServlet("/blog_edit")
public class BlogEditServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录，无法发布博客！");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录，无法发布博客！");
            return;
        }
        req.setCharacterEncoding("utf8");
        String tittle = req.getParameter("tittle");
        String content = req.getParameter("content");
        if (tittle == null || tittle.equals("") || content == null || content.equals("")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前提交的数据有误！标题或者正文为空！");
            return;
        }
        int blogId = Integer.parseInt(req.getParameter("blogId"));

        if (blogId == -1) {
            //发布博客功能
            Blog blog = new Blog();
            blog.setTittle(tittle);
            blog.setContent(content);
            blog.setUserId(user.getUserId());
            blog.setPostTime(new Timestamp(System.currentTimeMillis()));

            BlogDao blogDao = new BlogDao();
            blogDao.addBlog(blog);

            resp.sendRedirect("blog_list.html");
        } else {
            //编辑博客的功能
            resp.setContentType("text/html,charset=utf8");
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectById(blogId);
            blog.setTittle(tittle);
            blog.setContent(content);
            blogDao.modifyBlog(blog);
            resp.sendRedirect("blog_content.html?blogId=" + blogId);
        }
    }
}
